package apobates.gui.formatter;

import apobates.gui.formatter.packet.ResourceType;
import apobates.gui.formatter.reader.RemoteForm;
import apobates.gui.formatter.service.RecentExecutorService;
import apobates.gui.formatter.service.RemoteFormLoaderService;
import apobates.gui.formatter.storage.RecentRecord;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.util.Optional;
import java.util.function.Consumer;

/**
 * 从文件内容中获取JSON
 */
public class LocalFileJSONController {
    @FXML
    private VBox localFileTab;
    @FXML
    private TextField rourcePath;
    @FXML
    private ComboBox rourceCharset;
    @FXML
    private Button requestFileBtn;
    @FXML
    private Button cancelRequestFileBtn;
    @FXML
    private ListView<String> localHistory;
    // 资源请求表单
    private RemoteForm remoteForm = new RemoteForm();
    private RecentExecutorService recentExecutorService;


    @FXML
    public void initialize(){
        // 增加ComboBox
        rourceCharset.getItems().addAll(RecentExecutorService.getSupportCharset());
        // 将输入控件与form绑定::双向绑定
        // 文件地址
        remoteForm.filePathProperty().bindBidirectional(rourcePath.textProperty());
        // 字符集
        rourceCharset.valueProperty().bindBidirectional(remoteForm.fileEncodingProperty());
        // 超时
        remoteForm.setTimeout(8000);
        // 请求类型
        remoteForm.setType(ResourceType.FILE);
        // 最近记录执行器@20230402
        recentExecutorService = new RecentExecutorService(remoteForm);
        recentExecutorService.initialize(localHistory, ResourceType.FILE);
        localHistory.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue)-> {
            System.out.println("[RFLS][JRC-FILE]show click history::"+newValue);
            // 将选中的值放回到表单中
            Optional<RecentRecord> recentRecord = recentExecutorService.getRecentRecordCodec().decode(newValue);
            if(recentRecord.isPresent()) {
                remoteForm.setFilePath(recentRecord.get().getPath());
            }
        });
    }

    @FXML
    protected void requestFileAction(ActionEvent event){
        // 按钮的设置 @20230305-2
        requestFileBtn.setDisable(true);
        requestFileBtn.setText("请求中");
        // 回调
        Consumer<Boolean> fallbackFun = (t1)->{
            System.out.println("[RFLS][JRC-FILE]fallback handler status:"+t1);
            if(null != t1 && t1) {
                // 记录请求记录@20230402
                this.recentExecutorService.cache();
                // 关闭
                getCurrentStage().close();
            }
            if(null == t1 || !t1){
                this.requestFail();
            }
        };
        // 资源类型,
        // 若是能通过ToggleGroup能获取到可删除
        String s = "文件";
        System.out.println("[JRC][RRA-FILE]current resource type:"+s);
        // 2.执行加载
        RemoteFormLoaderService remoteFormLoaderService = new RemoteFormLoaderService(remoteForm);
        // 3.侦听成功状态(有变化时)/若无变化不会执行
        remoteFormLoaderService.setCallbackFun(fallbackFun);
        remoteFormLoaderService.stream().subscribe((booleanChange)->{
            Boolean t1 = booleanChange.getNewValue();
            System.out.println("[FRLS][JRC-FILE]stream subscribe status: "+t1);
        });
        remoteFormLoaderService.load(null);
    }

    @FXML
    protected void cancelRequestFileAction(ActionEvent event){
        getCurrentStage().close();
    }

    //浏览文件
    @FXML
    protected void browseFileAction(ActionEvent event){
        System.out.println("[JRC-FILE]browse filesystem start");
        Stage curStage = getCurrentStage();
        final FileChooser fileChooser = new FileChooser();
        configureFileChooser(fileChooser);
        File file = fileChooser.showOpenDialog(curStage);
        if (file != null) {
            rourcePath.setText(file.getPath());
        }
    }
    private Stage getCurrentStage(){
        return (Stage) localFileTab.getScene().getWindow();
    }
    private static void configureFileChooser(final FileChooser fileChooser) {
        fileChooser.setTitle("Choose json or txt file");
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("JSON files (*.json)", "*.json"),
                new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt")
        );
    }

    private void requestFail(){
        System.out.println("[JRC-FILE]request resource record fail. print resource:::");
        System.out.println(remoteForm);
        // 删除无效的最近记录
        this.recentExecutorService.delete(remoteForm.getType(), remoteForm.getFilePath());
        //
        Alert noConTip = new Alert(Alert.AlertType.ERROR, "文件目前暂时无法访问", ButtonType.OK);
        // 置顶
        Stage stage = (Stage) noConTip.getDialogPane().getScene().getWindow();
        stage.setAlwaysOnTop(true);
        stage.toFront(); // not sure if necessary
        noConTip.showAndWait().ifPresent(response -> {
            if (response == ButtonType.OK) {
                // 解除禁止
                requestFileBtn.setDisable(false);
                requestFileBtn.setText("开始");
            }
        });
    }
}
